#include "tools/list.h"

void list_init(list_t *list){
    list->count=0;
    list->first=list->last=(list_node_t *)0;
};

void list_insert_first(list_t *list, list_node_t *node){
    //判断node是否在list里面
    // 这里要求节点一定不在列表里，不然会破坏链表结构
    list_node_t *curr=list->first;
    while(curr != 0){
        if(curr == node){
            break;
        }
        curr = curr->next;
    }
    if(curr != 0){
        return ; // 节点在列表中
    }

    //清空node原来的值
    list_node_init(node);
    
    list_node_t *origin_first=list->first;
    if(origin_first){
        origin_first->pre=node;
        node->next=origin_first;
    }else{
        list->last=node;//为空，头部尾部都是node
    }
    list->first=node;
    list->count++;


};

void list_insert_last(list_t *list, list_node_t *node){
    //判断node是否在list里面
    // 这里要求节点一定不在列表里，不然会破坏链表结构
    list_node_t *curr=list->first;
    while(curr != 0){
        if(curr == node){
            break;
        }
        curr = curr->next;
    }
    if(curr != 0){
        return ; // 节点在列表中
    }

    //清空node原来的值
    list_node_init(node);

    list_node_t *origin_last=list->last;
    if(origin_last){
        origin_last->next=node;
        node->pre=origin_last;
    }else{
        list->first=node;//为空，头部尾部都是node
    }
    list->last=node;
    list->count++;
};

list_node_t* list_remove_first(list_t *list){
    if(list_is_empty(list)){
        return (list_node_t *)0;
    }
    list_node_t *origin_first=list->first;
    list->first=origin_first->next;
    list->count--;
    if(!list->first){
        //为空节点
        list->last=(list_node_t*)0;
    }else{
        list->first->pre=(list_node_t*)0;
    }
    origin_first->next=origin_first->pre=(list_node_t *)0;
    return origin_first;
};

list_node_t* list_remove(list_t *list, list_node_t *node){
    //判断node是否在list里面
    list_node_t *curr=list->first;
    while(curr != 0){
        if(curr == node){
            break;
        }
        curr = curr->next;
    }
    if(curr == 0){
        return 0; // 节点不在列表中
    }


    //node在list里面
    if(node==list->first){
        list->first=node->next;
    }

    if(node==list->last){
        list->last=node->pre;
    }

    if(node->pre){
        node->pre->next=node->next;
    }

    if(node->next){
        node->next->pre=node->pre;
    }
    list->count--;
    node->next=node->pre=(list_node_t*)0;
    return node;
};